from io import BytesIO
from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import HttpResponse, render, redirect

from web import models
from web.forms import account
from utils.image_code import check_code
import uuid
import datetime


def tencent_sms(request):
    '''腾讯发送接口'''
    dic = {
        'status': 1,
        'msg': ''
    }
    form = account.tencent_sms(request, data=request.GET)
    # print(request.GET)  # urlencode---<QueryDict: {'telephone': [''], 'tpl': ['register']}>
    if form.is_valid():
        return JsonResponse(dic)
    dic['status'] = 0
    dic['msg'] = form.errors
    return JsonResponse(dic)


# django运行时函数
def register(request):
    '''注册'''
    dic = {
        'status': 1,
        'msg': ''
    }
    if request.method == 'GET':
        form = account.register()
        return render(request, 'register.html', locals())
    form = account.register(data=request.POST)
    if form.is_valid():
        # 保存数据 instance-- 当前创建的对象
        instance = form.save()
        # price_policy
        price_policy = models.PricePolicy.objects.filter(title='个人免费版', category=1).first()
        # 创建交易记录
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user_info=instance,
            price_policy=price_policy,
            start_time=datetime.datetime.now(),
            num=0,
        )

        return JsonResponse(dic)
    dic['status'] = 0
    dic['msg'] = form.errors
    return JsonResponse(dic)


def login_sms(request):
    '''短信登录'''
    dic = {
        'status': 1,
        'msg': ''
    }
    if request.method == 'GET':
        return render(request, 'login_sms.html')
    form = account.login_sms(data=request.POST)
    if form.is_valid():
        telephone = form.cleaned_data.get('telephone')
        user_obj = models.user_info.objects.filter(telephone=telephone).first()
        request.session['user_id'] = user_obj.id
        return JsonResponse(dic)
    dic['status'] = 0
    dic['msg'] = form.errors
    return JsonResponse(dic)


def login_code(request):
    '''验证码登录'''
    if request.method == 'GET':
        return render(request, 'login_code.html')
    form = account.login_code(request, data=request.POST)
    if form.is_valid():
        return redirect('home')
    return render(request, 'login_code.html', locals())


def home(request):
    '''home页面'''
    return render(request, 'home.html')


def image_code(request):
    """ 生成图片验证码 """

    image_object, code = check_code()

    request.session['image_code'] = code
    request.session.set_expiry(60)  # 主动修改session的过期时间为60s
    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def login_out(request):
    request.session.flush()
    return redirect('home')


